import extend from 'dva-model-extend'
import settings from '@/settings'
import model from '@/baseModel'
import { /*user_save, */user, users, all_units, all_roles } from '@/services/api'

const { pagination/*, code*/ } = settings

export default extend(model, {
	namespace: 'user',
	state: {
		units: [],
		roles: [],
		roleIds: []
	},
	effects: {
		*reset(_, {
			put
		}) {
			yield put({
				type: 'updateState',
				payload: {
					data: undefined,
					roleIds: []
				}
			})
		},
		// *save({
		// 	payload
		// }, {
		// 	call,
		// 	select,
		// 	put
		// }) {
		// 	const {
		// 		callback,
		// 		...restParams
		// 	} = payload
		// 	const data = yield call(user_save, restParams)
		// 	if (data.code === code) {
		// 		callback && callback()
		// 		const { params } = yield select(_ => _.user)
		// 		yield put({
		// 			type: 'fetchAll',
		// 			payload: params
		// 		})
		// 	}
		// },
		*fetchOne({
			payload
		}, {
			call,
			put
		}) {
			const { data={} } = yield call(user, payload)
			const {
				roles=[],
				...rest
			} = data
			yield put({
				type: 'updateState',
				payload: {
					data: rest,
					roleIds: roles.map(_ => _.id)
				}
			})
		},
		*fetchAll({
			payload = pagination
		}, {
			call,
			put
		}) {
			const { data } = yield call(users, payload)
			yield put({
				type: 'updateState',
				payload: {
					list: data,
					params: payload
				}
			})
		},
		*fetchRoles({
			payload
		}, {
			call,
			put
		}) {
			const { data } = yield call(all_roles, payload)
			yield put({
				type: 'updateState',
				payload: {
					roles: data
				}
			})
		},
		*fetchUnits({
			payload
		}, {
			call,
			put
		}) {
			const { data } = yield call(all_units, payload)
			yield put({
				type: 'updateState',
				payload: {
					units: data
				}
			})
		}
	}
})